<template>
  <div class="page-builder">
    <!-- 顶部工具栏 -->
    <header class="toolbar">
      <div class="toolbar-left">
        <h1 class="app-title">
          <el-icon>
            <Grid />
          </el-icon>
          低代码页面构建器
        </h1>
      </div>

      <div class="toolbar-center">
        <el-button-group>
          <el-button size="small" @click="toggleGrid">
            <el-icon>
              <Grid />
            </el-icon>
            {{ showGrid ? '隐藏网格' : '显示网格' }}
          </el-button>
          <el-button size="small" @click="toggleRuler">
            <el-icon>
              <Setting />
            </el-icon>
            {{ showRuler ? '隐藏标尺' : '显示标尺' }}
          </el-button>
          <el-button size="small" @click="clearCanvas">
            <el-icon>
              <Delete />
            </el-icon>
            清空画布
          </el-button>
        </el-button-group>
      </div>

      <div class="toolbar-right">
        <el-button-group>
          <el-button type="success" size="small" @click="previewPage">
            <el-icon>
              <View />
            </el-icon>
            预览
          </el-button>
          <el-button type="primary" size="small" @click="savePage">
            <el-icon>
              <DocumentAdd />
            </el-icon>
            保存
          </el-button>
          <el-button size="small" @click="showLoadDialog = true">
            <el-icon>
              <FolderOpened />
            </el-icon>
            加载
          </el-button>
          <el-button size="small" @click="exportCode">
            <el-icon>
              <Download />
            </el-icon>
            导出代码
          </el-button>
        </el-button-group>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 左侧组件库 -->
      <aside class="component-library-panel">
        <ComponentLibrary />
      </aside>

      <!-- 中央设计画布 -->
      <section class="canvas-area">
        <div class="canvas-header">
          <div class="canvas-info">
            <span>画布尺寸: {{ canvasConfig.width }} × {{ canvasConfig.height }}</span>
            <span>组件数量: {{ components.length }}</span>
          </div>
          <ZoomToolbar
            :zoom-level="zoomLevel"
            :min="zoomConfig.min"
            :max="zoomConfig.max"
            @zoom-in="zoomIn"
            @zoom-out="zoomOut"
            @zoom-to="zoomTo"
            @fit="fitToScreen"
          />
        </div>

        <div class="canvas-container" :style="canvasContainerStyle" ref="canvasContainer">
          <div class="canvas-wrapper" :style="canvasWrapperStyle">
            <DesignCanvas ref="canvasRef" :style="canvasTransformStyle" />
          </div>
        </div>
      </section>

      <!-- 右侧属性面板 -->
      <aside class="properties-panel-area">
        <PropertiesPanel />
      </aside>
    </main>

    <!-- 页面预览对话框 -->
    <PreviewDialog v-model="showPreview" />

    <!-- 加载页面对话框 -->
    <LoadDialog v-model="showLoadDialog" @load="loadPage" />

    <!-- 导出代码对话框 -->
    <ExportDialog
      v-model="showExportDialog"
      :components="components"
      :canvas-config="canvasConfig"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useEditorStore } from '@/stores/editor'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid,
  Delete,
  View,
  DocumentAdd,
  FolderOpened,
  Download,
  Setting,
} from '@element-plus/icons-vue'

// 组件引入
import ComponentLibrary from '@/components/ComponentLibrary.vue'
import DesignCanvas from '@/components/DesignCanvas.vue'
import PropertiesPanel from '@/components/PropertiesPanel.vue'
import PreviewDialog from '@/components/PreviewDialog.vue'
import LoadDialog from '@/components/LoadDialog.vue'
import ExportDialog from '@/components/ExportDialog.vue'
import ZoomToolbar from '@/components/ZoomToolbar.vue'

const editorStore = useEditorStore()

// 界面状态
const showGrid = ref(true)
const showRuler = ref(false)
const showPreview = ref(false)
const showLoadDialog = ref(false)
const showExportDialog = ref(false)

// 画布引用
const canvasRef = ref(null)
const canvasContainer = ref(null)

// 计算属性
const components = computed(() => editorStore.components)
const canvasConfig = computed(() => editorStore.canvasConfig)
const zoomConfig = computed(() => editorStore.zoomConfig)
const zoomLevel = computed(() => zoomConfig.value.level)

const canvasContainerStyle = computed(() => ({
  overflow: 'auto',
  height: '100%',
  background: '#f0f2f5',
  position: 'relative',
}))

const canvasWrapperStyle = computed(() => ({
  minWidth: '100%',
  minHeight: '100%',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'flex-start',
  padding: '20px',
}))

const canvasTransformStyle = computed(() => ({
  transform: `scale(${zoomLevel.value})`,
  transformOrigin: 'top left',
  transition: 'transform 0.2s ease',
  border: '1px solid #ddd',
  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
  borderRadius: '4px',
  overflow: 'hidden',
  background: 'white',
}))

// 工具栏方法
const toggleGrid = () => {
  showGrid.value = !showGrid.value
  canvasRef.value?.toggleGrid()
}

const toggleRuler = () => {
  showRuler.value = !showRuler.value
  canvasRef.value?.toggleRuler()
}

const clearCanvas = async () => {
  try {
    await ElMessageBox.confirm('确定要清空画布吗？这将删除所有组件。', '清空画布', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    editorStore.clearCanvas()
    ElMessage.success('画布已清空')
  } catch {
    // 用户取消操作
  }
}

// 缩放控制
const zoomIn = () => {
  editorStore.zoomIn()
}

const zoomOut = () => {
  editorStore.zoomOut()
}

const resetZoom = () => {
  editorStore.resetZoom()
}

const fitToScreen = () => {
  if (canvasContainer.value && canvasRef.value) {
    const containerRect = canvasContainer.value.getBoundingClientRect()
    const canvasElement = canvasRef.value.$el

    // 获取容器大小（清除padding）
    const containerWidth = containerRect.width - 40 // 减去padding
    const containerHeight = containerRect.height - 40

    // 获取画布大小
    const canvasWidth = canvasElement.offsetWidth
    const canvasHeight = canvasElement.offsetHeight

    editorStore.fitToScreen(containerWidth, containerHeight, canvasWidth, canvasHeight)
  }
}

// 缩放到指定比例
const zoomTo = (level) => {
  editorStore.zoomTo(level)
}

// 键盘快捷键处理
const handleKeydown = (event) => {
  // Ctrl/Cmd + 缩放操作
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case '=':
      case '+':
        event.preventDefault()
        zoomIn()
        break
      case '-':
        event.preventDefault()
        zoomOut()
        break
      case '0':
        event.preventDefault()
        resetZoom()
        break
      case '1':
        event.preventDefault()
        fitToScreen()
        break
      case 's':
        event.preventDefault()
        savePage()
        break
      case 'o':
        event.preventDefault()
        showLoadDialog.value = true
        break
      case 'e':
        event.preventDefault()
        exportCode()
        break
      case 'p':
        event.preventDefault()
        previewPage()
        break
    }
  }
}

// 组件挂载和卸载
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  // 页面标题
  document.title = '低代码页面构建器'
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 页面操作
const previewPage = () => {
  showPreview.value = true
}

const savePage = async () => {
  try {
    const { value: pageName } = await ElMessageBox.prompt('请输入页面名称', '保存页面', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      inputValue: '我的页面',
      inputPattern: /.+/,
      inputErrorMessage: '页面名称不能为空',
    })

    editorStore.savePage(pageName)
    ElMessage.success(`页面 "${pageName}" 保存成功`)
  } catch {
    // 用户取消操作
  }
}

const loadPage = (pageData) => {
  editorStore.loadPage(pageData)
  showLoadDialog.value = false
  ElMessage.success('页面加载成功')
}

const exportCode = () => {
  if (components.value.length === 0) {
    ElMessage.warning('画布中没有组件，无法导出代码')
    return
  }
  showExportDialog.value = true
}
</script>

<style lang="scss" scoped>
.page-builder {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.toolbar {
  height: 60px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  .app-title {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
    color: #303133;
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: #409eff;
    }
  }

  .toolbar-center {
    flex: 1;
    display: flex;
    justify-content: center;
  }
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.component-library-panel {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
}

.canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.canvas-header {
  height: 40px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  font-size: 12px;
  color: #606266;

  .canvas-info {
    display: flex;
    gap: 20px;
  }

  .canvas-zoom {
    display: flex;
    align-items: center;
    gap: 8px;

    .zoom-label {
      font-size: 12px;
      color: #606266;
      margin-right: 4px;
    }

    .fit-screen-btn {
      margin-left: 8px;
    }
  }
}

.canvas-container {
  flex: 1;
  position: relative;
  overflow: auto;
}

.properties-panel-area {
  width: 300px;
  background: #fff;
  border-left: 1px solid #e4e7ed;
}

// 响应式设计
@media (max-width: 1200px) {
  .component-library-panel {
    width: 240px;
  }

  .properties-panel-area {
    width: 260px;
  }
}

@media (max-width: 768px) {
  .toolbar {
    padding: 0 12px;

    .app-title {
      font-size: 16px;
    }

    .toolbar-center {
      display: none;
    }
  }

  .component-library-panel {
    width: 200px;
  }

  .properties-panel-area {
    width: 220px;
  }
}
</style>
